#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(int argc, char* argv[]){
    pid_t pid, wpid;
    int i ;
    for (i = 0; i < 5; ++i) {
        pid = fork();
        if(pid == 0){ //循环期间子进程不执行fork
            break;
        }
    }

    if (5 == i){//父进程，只有父进程中i++才能等于5
        /*
        while ((wpid = (waitpid(-1,NULL,0)))){ //第三个参数0 表示阻塞的方式回收子进程
            printf("wait child %d \n",wpid);
            if(wpid == -1){
                break;
            }
        }*/
        while ((wpid = waitpid(-1,NULL,WNOHANG)) != -1){//使用非阻塞回收
            if (wpid > 0){
                printf("wait child %d \n",wpid);
            } else if (wpid == -1){
                sleep(1);
                continue;
            }
        }
    } else {
        sleep(1);
        printf("i'm %dth child ,pdi = %d\n",i,getpid());
    }
}